<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <form>
      <input type="file" id="file" />
      <input type="submit" value="提交" />
    </form>
    <div>
      <div>EventSource/SSE:</div>
      <div id="ssehtml"></div>
      <button id="ljsse">sse连接</button>
    </div>
    <div>
      <div>stream/SSE:</div>
      <div id="stream"></div>
      <button id="ssse">流连接</button>
    </div>
    <script>
      var file = document.querySelector("#file");
      let controller = new AbortController();
      //为选择文件表单添加onchanges事件，选择文件时触发
      file.onchange = function () {
        var formData = new FormData();
        //将用户选择的文件追加到form对象当中
        formData.append("attrName", this.files[0]);
        var xhr = new XMLHttpRequest();
        xhr.open("post", "http://localhost:7012/upload");
        xhr.send(formData);
        xhr.onload = function () {
          //如果请求成功
          if (xhr.status == 200) {
            console.log(xhr.responseText);
          }
        };
      };
      ljsse.onclick = sendsse;
      function sendsse() {
        const sse = new EventSource("http://localhost:7012/sse");
        sse.addEventListener("message", (e) => {
          console.log("---数据", e.data);
          ssehtml.innerHTML += e.data + "<br>";
        });
      }

      ssse.onclick = sendstream;
      async function sendstream() {
        const response = await fetch("http://localhost:7012/sse2", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Accept: "text/event-stream",
          },
          body: JSON.stringify({ text: "你是谁" }),
          signal: controller.signal,
        }).catch((err) => {
          console.log("err报错了", err);
        });
        // 获取 ReadableStream 并创建读取器
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        // 持续读取流数据
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            reader.releaseLock();
            break;
          } // 流结束

          const chunk = decoder.decode(value);
          stream.innerHTML += JSON.parse(chunk.split("data: ")[1]).text;
        }
      }
    </script>
  </body>
</html>
